<template>
	<view class="container">
		<!-- 欢迎语 -->
		<view class="login-title">
			<view>您好，</view>
			<view>欢迎登录车联网服务!</view>
		</view>
		<!-- 登录框 -->
		<view class="login-box">
			<input class="login-input" type="text" placeholder="请输入用户名" v-model="user.phone" />
			<view class="login-code">
				<input class="login-input" type="text" placeholder="请输入密码" v-model="user.code" />
				<button class="code-button">获取验证码</button>
			</view>
			<button class="login-button" @click="login">登 录</button>
			<button class="login-button" @click="register" style="background-color: #e5e8ec; color: #297cf7;">注 册</button>
		</view>

		<!-- 人物图 -->
		<view class="character">
			<image class="character-image" src="/static/login/loginbgp.png" />
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import request from '/pages/utils/request.js';
	import baseUrl from '/pages/utils/urlConfig';

	const user = ref({
		phone: 'zhangsan',
		code: '123456'
	})

	function login() {
		request({
			url: baseUrl + '/auth/userLogin',
			method: 'POST',
			data: {
				username: user.value.phone,
				password: user.value.code
			},
			success(res) {
				console.log(res.data.data.access_token)
				// 1. 解析返回数据（新结构：token + carUser）
				const tokenData = res.data.data.token; // 包含access_token和expires_in
				const carUser = res.data.data.carUser; // 用户详细信息

				// 2. 存储Token到缓存
				uni.setStorageSync('Token', tokenData.access_token);

				// 3. 存储用户信息到缓存（包括carUser）
				uni.setStorageSync('user', {
					...carUser, // 用户详细信息
					token: tokenData // 保留原token结构（可选）
				});

				// 4. 登录成功提示
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				});

				// 5. 跳转到首页
				uni.switchTab({
					url: '/pages/index/home/home'
				});
			}
		})
	}
	
	function register(){
		uni.navigateTo({
			url: '/pages/login/register/register'
		})
	}
</script>

<style scoped>
	.container {
		background-image: url(/static/login/loginbg.png);
		background-size: 100%;
		width: 100%;
	}

	.login-title {
		height: 180rpx;
		color: white;
		font-size: 16px;
		padding: 150rpx 0 0 100rpx;
	}

	.login-title :nth-child(1) {
		font-size: 23px;
		font-weight: 600;
		margin-bottom: 10px;
	}

	.character {
		position: absolute;
		top: 190rpx;
		left: 450rpx;
	}

	.character-image {
		width: 140px;
		height: 110px;
	}

	.login-box {
		height: 100vh;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 20px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		padding: 120rpx 80rpx;
	}

	.login-input {
		padding: 8px 4px;
		border-bottom: #d8d8d8 2px solid;
		margin-bottom: 25px;
	}

	.code-button {
		background-color: #4c8efe;
		color: #fff;
		font-size: 14px;
		width: 100px;
		height: 35px;
		border-radius: 17px;
		position: absolute;
		right: 80rpx;
		top: 580rpx;
	}

	.login-button {
		background-color: #297cf7;
		color: #fff;
		font-size: 16px;
		font-weight: bold;
		height: 44px;
		line-height: 44px;
		border-radius: 24px;
		margin: 30rpx auto;
	}
</style>